<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>一文彻底搞懂Zookeeper | 全栈进阶那些事</title><meta name="keywords" content="Zookeeper"><meta name="author" content="liuyuantao"><meta name="copyright" content="liuyuantao"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一文彻底搞懂Zookeeper">
<meta property="og:type" content="article">
<meta property="og:title" content="一文彻底搞懂Zookeeper">
<meta property="og:url" content="https://liuyuantao.gitee.io/2021/07/12/1e41bdf3e092.html">
<meta property="og:site_name" content="全栈进阶那些事">
<meta property="og:description" content="一文彻底搞懂Zookeeper">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200518143448459.png">
<meta property="article:published_time" content="2021-07-12T08:51:41.000Z">
<meta property="article:modified_time" content="2021-11-13T01:06:19.872Z">
<meta property="article:author" content="liuyuantao">
<meta property="article:tag" content="中间件">
<meta property="article:tag" content="Zookeeper">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200518143448459.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://liuyuantao.gitee.io/2021/07/12/1e41bdf3e092"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?d43383137144f76a37f1074576bc674e";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":500,"languages":{"author":"作者: liuyuantao","link":"链接: ","source":"来源: 全栈进阶那些事","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#2d3035","position":"top-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '一文彻底搞懂Zookeeper',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-11-13 09:06:19'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="全栈进阶那些事" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/zhiyao_avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">41</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">4</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">全栈进阶那些事</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">一文彻底搞懂Zookeeper</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2021-07-12T08:51:41.000Z" title="undefined 2021-07-12 16:51:41">2021-07-12</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E4%B8%AD%E9%97%B4%E4%BB%B6/">中间件</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="一文彻底搞懂Zookeeper"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>本文是基于CentOS 7.9系统环境，进行Zookeeper的学习和使用</p>
</blockquote>
<h1 id="1-Zookeeper简介"><a href="#1-Zookeeper简介" class="headerlink" title="1. Zookeeper简介"></a>1. Zookeeper简介</h1><h2 id="1-1-什么是Zookeeper"><a href="#1-1-什么是Zookeeper" class="headerlink" title="1.1 什么是Zookeeper"></a>1.1 什么是Zookeeper</h2><p>Zookeeper是一个开源的分布式的，为分布式应用提供协调服务的Apache项目。本质上，就是文件系统+通知机制</p>
<h2 id="1-2-Zookeeper工作机制"><a href="#1-2-Zookeeper工作机制" class="headerlink" title="1.2 Zookeeper工作机制"></a>1.2 Zookeeper工作机制</h2><p>Zookeeper从设计模式角度来理解：是一个基于观察者模式设计的分布式服务管理框架，它负责存储和管理大家都关心的数据，然后接受观察者的注册，一旦这些数据的状态发生变化，Zookeeper就负责通知已经在Zookeeper上注册的那些观察者做出相应的反应</p>
<p><img src="https://img-blog.csdnimg.cn/20200518143448459.png"></p>
<h2 id="1-3-Zookeeper特点"><a href="#1-3-Zookeeper特点" class="headerlink" title="1.3 Zookeeper特点"></a>1.3 Zookeeper特点</h2><p><img src="https://img-blog.csdnimg.cn/20200927144855252.png"></p>
<ol>
<li>Zookeeper：一各领导者（Leader），多个跟随者（Follower）组成的集群</li>
<li>集群中只要有半数以上节点存活，Zookeeper集群就能正常服务，所以zookeeper适合安装奇数台服务器</li>
<li>全局数据一致：每个server保存一份相同的数据副本，client无论连接到哪个server，数据都是一致的</li>
<li>更新请求顺序进行，来自同一个client的更新请求按其发送顺序依次执行</li>
<li>数据更新原子性，一次数据更新要么成功，要么失败</li>
<li>实时性，在一定时间范围内，client能读到最新数据</li>
</ol>
<h2 id="1-4-Zookeeper数据结构"><a href="#1-4-Zookeeper数据结构" class="headerlink" title="1.4 Zookeeper数据结构"></a>1.4 Zookeeper数据结构</h2><p>与Unix文件系统类似，整体上是一棵树，每一个节点称为znode，每一个znode默认存储1MB数据，每个znode都可以通过其路径唯一标识</p>
<h2 id="1-5-Zookeeper应用场景"><a href="#1-5-Zookeeper应用场景" class="headerlink" title="1.5 Zookeeper应用场景"></a>1.5 Zookeeper应用场景</h2><p>提供的服务包括：统一命名服务、统一配置管理、统一集群管理、服务器节点动态上下线、软负载均衡等</p>
<h3 id="1-5-1-统一命名服务"><a href="#1-5-1-统一命名服务" class="headerlink" title="1.5.1 统一命名服务"></a>1.5.1 统一命名服务</h3><p>在分布式环境下，经常需要对应用/服务进行统一命令，便于识别</p>
<h3 id="1-5-2-统一配置管理"><a href="#1-5-2-统一配置管理" class="headerlink" title="1.5.2 统一配置管理"></a>1.5.2 统一配置管理</h3><ul>
<li>分布式环境下，配置文件同步非常常见</li>
</ul>
<p>（1）一般要求一个集群中，所有节点的配置信息是一致的，比如kafka集群；<br>（2）对配置文件修改后，希望能够快速同步到各个节点上。</p>
<ul>
<li>配置管理可交由zookeeper实现</li>
</ul>
<p>（1）可将配置信息写入Zookeeper上的一个Znode；<br>（2）各个客户端服务器监听这个Znode；<br>（3）一旦Znode中的数据被修改，Zookeeper将通知各个客户端服务器。</p>
<h3 id="1-5-3-统一集群管理"><a href="#1-5-3-统一集群管理" class="headerlink" title="1.5.3 统一集群管理"></a>1.5.3 统一集群管理</h3><p>分布式环境下，实时掌握每个节点的状态是必要的<br>（1）可根据节点实时状态做出一些调整。<br>Zookeeper可以实现实时监控节点状态变化<br>（1）可将节点信息写入Zookeeper上的一个Znode；<br>（2）监听这个Znode可获取它的实时状态变化。</p>
<h3 id="1-5-4-服务器节点动态上下线"><a href="#1-5-4-服务器节点动态上下线" class="headerlink" title="1.5.4 服务器节点动态上下线"></a>1.5.4 服务器节点动态上下线</h3><p>客户端能实时洞察到服务器上下线的变化</p>
<h3 id="1-5-5-软负载均衡"><a href="#1-5-5-软负载均衡" class="headerlink" title="1.5.5 软负载均衡"></a>1.5.5 软负载均衡</h3><p>在Zookeeper中记录每台服务器的访问数，让访问数最少的服务器去处理最新的客户端请求</p>
<h2 id="1-6-Zookeeper选举机制"><a href="#1-6-Zookeeper选举机制" class="headerlink" title="1.6 Zookeeper选举机制"></a>1.6 Zookeeper选举机制</h2><ul>
<li>半数机制：集群中半数以上机器存活，集群可用。所以Zookeeper适合安装奇数台服务器。</li>
<li>Zookeeper虽然在配置文件中并没有指定Master和Slave。但是，Zookeeper工作时，是有一个节点为Leader，其他则为Follower，Leader是通过内部的选举机制临时产生的。</li>
<li>以一个简单的例子来说明整个选举的过程。</li>
</ul>
<p>假设有五台服务器组成的Zookeeper集群，它们的id从1-5，同时它们都是最新启动的，也就是没有历史数据，在存放数据量这一点上，都是一样的。假设这些服务器依序启动，来看看会发生什么。<br>（1）服务器1启动，发起一次选举；<br>所有的服务器节点都会选自己作为leader， 此时服务器1投自己1票，但是只有它一台服务器启动了，它发出去的报文没有任何响应，所以选举无法完成；<br>服务器1的状态一直是LOOKING状态。<br>（2）服务器2启动，再发起一次选举；<br>服务器1和服务器2分别投自己1票，服务器之间进行通信，互相交换自己的选举结果，由于两者都没有历史选举数据，所以id值较大的服务器2胜出，服务器1更改投票为服务器2，但是由于没有达到超过半数以上的服务器都同意选举它(这个例子中的半数以上是3)，所以选举无法完成；<br>所以服务器1、2还是继续保持LOOKING状态。<br>（3）服务器3启动，根据前面的理论分析，服务器3成为服务器1、2、3中的老大，而与上面不同的是，此时有三台服务器选举了它，所以它成为了这次选举的Leader,；<br>服务器1、2还是更改状态为FOLLOWING状态，服务器3更改状态为LEADING。<br>（4）服务器4启动，发起一次选举；<br>此时，服务器1，2，3已经不是LOOKING状态，不会更改投票信息，服务器3会有3票，服务器4会投自己1票<br>根据少数服从多数，服务器4会更改自己的投票结果为服务器3；<br>服务器4更改状态为FOLLOWING状态<br>（5）服务器5启动，同4一样当小弟。</p>
<h2 id="1-7-Zookeeper节点类型"><a href="#1-7-Zookeeper节点类型" class="headerlink" title="1.7 Zookeeper节点类型"></a>1.7 Zookeeper节点类型</h2><ul>
<li>持久</li>
</ul>
<p>客户端和服务端断开连接后，创建的节点不删除</p>
<ul>
<li>短暂</li>
</ul>
<p>客户端和服务端断开连接后，创建的节自己删除</p>
<ul>
<li>顺序编号</li>
</ul>
<p>创建znode时设置顺序标识，znode名称后会附加一个值，顺序号是一个单调递增的计数器，由父节点维护；在分布式系统中，顺序号可以被用于为所有的事件进行全局排序，这样客户端可以通过顺序号推断事件的顺序</p>
<ol>
<li>持久化目录节点：客户端与zookeeper断开连接后，该节点依旧存在</li>
<li>持久化顺序编号目录节点：客户端与zookeeper断开连接后，该节点依旧存在，只是zookeeper在创建该节点时进行顺序编号</li>
<li>临时目录节点：客户端与zookeeper断开连接后，该节点被删除</li>
<li>临时顺序编号目录节点：客户端与zookeeper断开连接后，该节点被删除，只是zookeeper在创建该节点时进行顺序编号</li>
</ol>
<h2 id="1-8-Zookeeper监听器原理"><a href="#1-8-Zookeeper监听器原理" class="headerlink" title="1.8 Zookeeper监听器原理"></a>1.8 Zookeeper监听器原理</h2><h3 id="1-8-1-常见的监听类型"><a href="#1-8-1-常见的监听类型" class="headerlink" title="1.8.1 常见的监听类型"></a>1.8.1 常见的监听类型</h3><p>监听节点数据的变化</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">get path [watch]</span><br></pre></td></tr></table></figure>

<p>监听子节点增减的变化</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ls path [watch]</span><br></pre></td></tr></table></figure>

<h3 id="1-8-2-监听器原理详解"><a href="#1-8-2-监听器原理详解" class="headerlink" title="1.8.2 监听器原理详解"></a>1.8.2 监听器原理详解</h3><p><img src="https://img-blog.csdnimg.cn/20200519104636710.png"></p>
<ol>
<li>首先要有一个main()线程</li>
<li>在main()线程中创建zookeeper客户端，这时就会创建两个线程，一个负责网络连接通信（connect），一个负责监听（listener）</li>
<li>通过connect线程将注册的监听事件发送给zookeeper</li>
<li>在zookeeper的注册监听器列表中将注册的监听事件添加到列表中</li>
<li>zookeeper监听到有数据或路径变化，就会将这个消息发送给listener线程</li>
<li>listener线程内部调用了process()方法</li>
</ol>
<h2 id="1-9-Zookeeper写数据原理"><a href="#1-9-Zookeeper写数据原理" class="headerlink" title="1.9 Zookeeper写数据原理"></a>1.9 Zookeeper写数据原理</h2><p><img src="https://img-blog.csdnimg.cn/20200519111416515.png">  </p>
<h1 id="2-Zookeeper单节点standalone安装"><a href="#2-Zookeeper单节点standalone安装" class="headerlink" title="2. Zookeeper单节点standalone安装"></a>2. Zookeeper单节点standalone安装</h1><h2 id="2-1-集群规划"><a href="#2-1-集群规划" class="headerlink" title="2.1 集群规划"></a>2.1 集群规划</h2><p>hostname|    CPU |    内存|    组件|    IP地址<br>|—|—|—|—|—<br>hadoop101|    2    |4G|    Zookeeper|    192.168.1.100</p>
<h2 id="2-2-解压安装"><a href="#2-2-解压安装" class="headerlink" title="2.2 解压安装"></a>2.2 解压安装</h2><p>节点下分别执行</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">tar -zxvf zookeeper-3.4.10.tar.gz -C /opt/module/</span><br><span class="line">mv zookeeper-3.4.10 zookeeper</span><br></pre></td></tr></table></figure>

<h2 id="2-3-配置zoo-cfg文件"><a href="#2-3-配置zoo-cfg文件" class="headerlink" title="2.3 配置zoo.cfg文件"></a>2.3 配置zoo.cfg文件</h2><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">mv zoo_sample.cfg zoo.cfg</span><br><span class="line">vi zoo.cfg</span><br><span class="line"><span class="comment"># 修改如下信息</span></span><br><span class="line">dataDir=/opt/module/zookeeper/zk-Data</span><br></pre></td></tr></table></figure>

<h2 id="2-4-启动集群"><a href="#2-4-启动集群" class="headerlink" title="2.4 启动集群"></a>2.4 启动集群</h2><p>节点下分别执行</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">bin/zkServer.sh start</span><br></pre></td></tr></table></figure>

<p>成功启动输出信息</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">[lytdev@es201 bin]$ ./zkServer.sh start</span><br><span class="line">ZooKeeper JMX enabled by default</span><br><span class="line">Using config: /opt/module/zookeeper/bin/../conf/zoo.cfg</span><br><span class="line">Starting zookeeper ... STARTED</span><br></pre></td></tr></table></figure>

<h2 id="2-5-查看集群状态"><a href="#2-5-查看集群状态" class="headerlink" title="2.5 查看集群状态"></a>2.5 查看集群状态</h2><p>节点下分别执行</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">bin/zkServer.sh status</span><br></pre></td></tr></table></figure>

<p>成功启动输出信息</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">[lytdev@es201 bin]$ ./zkServer.sh status</span><br><span class="line">ZooKeeper JMX enabled by default</span><br><span class="line">Using config: /opt/module/zookeeper/bin/../conf/zoo.cfg</span><br><span class="line">Mode: standalone</span><br></pre></td></tr></table></figure>

<h1 id="3-Zookeeper分布式安装"><a href="#3-Zookeeper分布式安装" class="headerlink" title="3. Zookeeper分布式安装"></a>3. Zookeeper分布式安装</h1><h2 id="3-1-集群规划"><a href="#3-1-集群规划" class="headerlink" title="3.1 集群规划"></a>3.1 集群规划</h2><p>hostname|CPU|内存|组件IP地址<br>|—|—|—|—|<br>hadoop101|2|4G|Zookeeper|192.168.1.100<br>hadoop104|2|4G|Zookeeper|192.168.1.101<br>hadoop105|2|4G|Zookeeper|192.168.1.102</p>
<h2 id="3-2-解压安装"><a href="#3-2-解压安装" class="headerlink" title="3.2 解压安装"></a>3.2 解压安装</h2><p>三个节点下分别执行</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">tar -zxvf zookeeper-3.4.10.tar.gz -C /opt/module/</span><br></pre></td></tr></table></figure>

<h2 id="3-3-配置服务器编号"><a href="#3-3-配置服务器编号" class="headerlink" title="3.3 配置服务器编号"></a>3.3 配置服务器编号</h2><p><strong>hadoop101 节点下</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">mkdir -p zkData</span><br><span class="line"><span class="built_in">cd</span> zkData</span><br><span class="line">vi myid</span><br><span class="line"><span class="comment"># 添加如下信息</span></span><br><span class="line">1</span><br></pre></td></tr></table></figure>

<p><strong>hadoop104 节点下</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">mkdir -p zkData</span><br><span class="line"><span class="built_in">cd</span> zkData</span><br><span class="line">vi myid</span><br><span class="line"><span class="comment"># 添加如下信息</span></span><br><span class="line">4</span><br></pre></td></tr></table></figure>

<p><strong>hadoop105 节点下</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">mkdir -p zkData</span><br><span class="line"><span class="built_in">cd</span> zkData</span><br><span class="line">vi myid</span><br><span class="line"><span class="comment"># 添加如下信息</span></span><br><span class="line">5</span><br></pre></td></tr></table></figure>

<h2 id="3-4-配置zoo-cfg文件"><a href="#3-4-配置zoo-cfg文件" class="headerlink" title="3.4 配置zoo.cfg文件"></a>3.4 配置zoo.cfg文件</h2><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">mv zoo_sample.cfg zoo.cfg</span><br><span class="line">vi zoo.cfg</span><br><span class="line"><span class="comment"># 修改如下信息</span></span><br><span class="line">dataDir=/opt/module/zookeeper-3.4.10/zkData</span><br><span class="line"><span class="comment"># 添加如下信息</span></span><br><span class="line">server.1=hadoop101:2888:3888</span><br><span class="line">server.4=hadoop104:2888:3888</span><br><span class="line">server.5=hadoop105:2888:3888</span><br></pre></td></tr></table></figure>

<h2 id="3-5-启动集群"><a href="#3-5-启动集群" class="headerlink" title="3.5 启动集群"></a>3.5 启动集群</h2><p>三个节点下分别执行</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">bin/zkServer.sh start</span><br></pre></td></tr></table></figure>

<h2 id="3-6-查看集群状态"><a href="#3-6-查看集群状态" class="headerlink" title="3.6 查看集群状态"></a>3.6 查看集群状态</h2><p>三个节点下分别执行</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">bin/zkServer.sh status</span><br></pre></td></tr></table></figure>

<h1 id="4-Zookeeper的使用"><a href="#4-Zookeeper的使用" class="headerlink" title="4. Zookeeper的使用"></a>4. Zookeeper的使用</h1><h2 id="4-1-客户端命令行操作"><a href="#4-1-客户端命令行操作" class="headerlink" title="4.1 客户端命令行操作"></a>4.1 客户端命令行操作</h2><p>基本语法|功能描述<br>|—|—<br>help|显示所有操作命令<br>ls path [watch]|使用ls命令来查看当前znode中所包含的内容<br>ls2 path [watch]|查看当前节点数据并能看到更新次数等数据<br>create|普通创建<br>create -s|含有序列<br>create -e|临时创建（重启或者超时消失）<br>get path [watch]|获得节点的值<br>set|设置节点的具体值<br>stat|查看节点状态<br>delete|删除节点<br>deleteall|递归删除节点</p>
<p>** 启动客户端**</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">bin/zkCli.sh</span><br></pre></td></tr></table></figure>

<p><strong>查看当前znode所包含的内容</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ls /</span><br></pre></td></tr></table></figure>

<p><strong>查看当前znode节点详细数据</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ls2 /</span><br></pre></td></tr></table></figure>

<p><strong>创建znode节点</strong></p>
<p>create /sanguo “lytdev”</p>
<p><strong>获取znode节点的值</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">get /sanguo</span><br><span class="line">get /sanguo/shuguo</span><br></pre></td></tr></table></figure>

<p><strong>创建短暂的znode节点</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">create -e /sanguo/wuguo <span class="string">&quot;sunquan&quot;</span></span><br></pre></td></tr></table></figure>

<p><strong>退出客户端</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">quit</span><br></pre></td></tr></table></figure>

<p><strong>创建带顺序号的znode节点</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">create -s /sanguo/weiguo <span class="string">&quot;caocao&quot;</span></span><br></pre></td></tr></table></figure>

<p><strong>修改znode节点的值</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="built_in">set</span> /sanguo <span class="string">&quot;diaochan&quot;</span></span><br></pre></td></tr></table></figure>

<p><strong>监听znode节点的值的变化（只能监听一次）</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">get /sanguo watch</span><br></pre></td></tr></table></figure>

<p><strong>监听znode节点的子节点变化（只能监听一次）</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">ls /sanguo watch</span><br></pre></td></tr></table></figure>

<p><strong>删除znode节点</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">delete /sanguo/wuguo</span><br></pre></td></tr></table></figure>

<p><strong>递归删除znode节点</strong></p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">rmr /sanguo</span><br></pre></td></tr></table></figure>

<h1 id="5-Zookeeper的面试重点"><a href="#5-Zookeeper的面试重点" class="headerlink" title="5. Zookeeper的面试重点"></a>5. Zookeeper的面试重点</h1><h2 id="5-1-如何保持数据全局一致性"><a href="#5-1-如何保持数据全局一致性" class="headerlink" title="5.1 如何保持数据全局一致性"></a>5.1 如何保持数据全局一致性</h2><p>zookeeper通过Zab协议保持数据全局一致性</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined" rel="external nofollow noreferrer">liuyuantao</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuyuantao.gitee.io/2021/07/12/1e41bdf3e092.html">https://liuyuantao.gitee.io/2021/07/12/1e41bdf3e092.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuyuantao.gitee.io" target="_blank">全栈进阶那些事</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E4%B8%AD%E9%97%B4%E4%BB%B6/">中间件</a><a class="post-meta__tags" href="/tags/Zookeeper/">Zookeeper</a></div><div class="post_share"><div class="social-share" data-image="https://img-blog.csdnimg.cn/20200518143448459.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/qr_code_wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/img/qr_code_wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/qr_code_alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/img/qr_code_alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/09/12/a99eab3d4a13.html"><img class="prev-cover" src="https://oscimg.oschina.net/oscnet/20200617165336828.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">一文彻底搞懂Flume</div></div></a></div><div class="next-post pull-right"><a href="/2020/11/07/fd53f751c2eb.html"><img class="next-cover" src="https://oscimg.oschina.net/oscnet/c646ab2c9196c3eacc49b81b10d47f7a191.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Hadoop3.X分布式运行环境搭建手记</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/10/12/245dd8355f34.html" title="一文彻底搞懂Kafka"><img class="cover" src="https://img-blog.csdnimg.cn/20200620092054385.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-10-12</div><div class="title">一文彻底搞懂Kafka</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#1-Zookeeper%E7%AE%80%E4%BB%8B"><span class="toc-text">1. Zookeeper简介</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-1-%E4%BB%80%E4%B9%88%E6%98%AFZookeeper"><span class="toc-text">1.1 什么是Zookeeper</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-2-Zookeeper%E5%B7%A5%E4%BD%9C%E6%9C%BA%E5%88%B6"><span class="toc-text">1.2 Zookeeper工作机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-3-Zookeeper%E7%89%B9%E7%82%B9"><span class="toc-text">1.3 Zookeeper特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-4-Zookeeper%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-text">1.4 Zookeeper数据结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-5-Zookeeper%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-text">1.5 Zookeeper应用场景</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-1-%E7%BB%9F%E4%B8%80%E5%91%BD%E5%90%8D%E6%9C%8D%E5%8A%A1"><span class="toc-text">1.5.1 统一命名服务</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-2-%E7%BB%9F%E4%B8%80%E9%85%8D%E7%BD%AE%E7%AE%A1%E7%90%86"><span class="toc-text">1.5.2 统一配置管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-3-%E7%BB%9F%E4%B8%80%E9%9B%86%E7%BE%A4%E7%AE%A1%E7%90%86"><span class="toc-text">1.5.3 统一集群管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-4-%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%8A%82%E7%82%B9%E5%8A%A8%E6%80%81%E4%B8%8A%E4%B8%8B%E7%BA%BF"><span class="toc-text">1.5.4 服务器节点动态上下线</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-5-5-%E8%BD%AF%E8%B4%9F%E8%BD%BD%E5%9D%87%E8%A1%A1"><span class="toc-text">1.5.5 软负载均衡</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-6-Zookeeper%E9%80%89%E4%B8%BE%E6%9C%BA%E5%88%B6"><span class="toc-text">1.6 Zookeeper选举机制</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-7-Zookeeper%E8%8A%82%E7%82%B9%E7%B1%BB%E5%9E%8B"><span class="toc-text">1.7 Zookeeper节点类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-8-Zookeeper%E7%9B%91%E5%90%AC%E5%99%A8%E5%8E%9F%E7%90%86"><span class="toc-text">1.8 Zookeeper监听器原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-8-1-%E5%B8%B8%E8%A7%81%E7%9A%84%E7%9B%91%E5%90%AC%E7%B1%BB%E5%9E%8B"><span class="toc-text">1.8.1 常见的监听类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-8-2-%E7%9B%91%E5%90%AC%E5%99%A8%E5%8E%9F%E7%90%86%E8%AF%A6%E8%A7%A3"><span class="toc-text">1.8.2 监听器原理详解</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-9-Zookeeper%E5%86%99%E6%95%B0%E6%8D%AE%E5%8E%9F%E7%90%86"><span class="toc-text">1.9 Zookeeper写数据原理</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#2-Zookeeper%E5%8D%95%E8%8A%82%E7%82%B9standalone%E5%AE%89%E8%A3%85"><span class="toc-text">2. Zookeeper单节点standalone安装</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#2-1-%E9%9B%86%E7%BE%A4%E8%A7%84%E5%88%92"><span class="toc-text">2.1 集群规划</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-2-%E8%A7%A3%E5%8E%8B%E5%AE%89%E8%A3%85"><span class="toc-text">2.2 解压安装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-3-%E9%85%8D%E7%BD%AEzoo-cfg%E6%96%87%E4%BB%B6"><span class="toc-text">2.3 配置zoo.cfg文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-4-%E5%90%AF%E5%8A%A8%E9%9B%86%E7%BE%A4"><span class="toc-text">2.4 启动集群</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-5-%E6%9F%A5%E7%9C%8B%E9%9B%86%E7%BE%A4%E7%8A%B6%E6%80%81"><span class="toc-text">2.5 查看集群状态</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#3-Zookeeper%E5%88%86%E5%B8%83%E5%BC%8F%E5%AE%89%E8%A3%85"><span class="toc-text">3. Zookeeper分布式安装</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#3-1-%E9%9B%86%E7%BE%A4%E8%A7%84%E5%88%92"><span class="toc-text">3.1 集群规划</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-2-%E8%A7%A3%E5%8E%8B%E5%AE%89%E8%A3%85"><span class="toc-text">3.2 解压安装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-3-%E9%85%8D%E7%BD%AE%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BC%96%E5%8F%B7"><span class="toc-text">3.3 配置服务器编号</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-4-%E9%85%8D%E7%BD%AEzoo-cfg%E6%96%87%E4%BB%B6"><span class="toc-text">3.4 配置zoo.cfg文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-5-%E5%90%AF%E5%8A%A8%E9%9B%86%E7%BE%A4"><span class="toc-text">3.5 启动集群</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-6-%E6%9F%A5%E7%9C%8B%E9%9B%86%E7%BE%A4%E7%8A%B6%E6%80%81"><span class="toc-text">3.6 查看集群状态</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#4-Zookeeper%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">4. Zookeeper的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#4-1-%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%91%BD%E4%BB%A4%E8%A1%8C%E6%93%8D%E4%BD%9C"><span class="toc-text">4.1 客户端命令行操作</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#5-Zookeeper%E7%9A%84%E9%9D%A2%E8%AF%95%E9%87%8D%E7%82%B9"><span class="toc-text">5. Zookeeper的面试重点</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#5-1-%E5%A6%82%E4%BD%95%E4%BF%9D%E6%8C%81%E6%95%B0%E6%8D%AE%E5%85%A8%E5%B1%80%E4%B8%80%E8%87%B4%E6%80%A7"><span class="toc-text">5.1 如何保持数据全局一致性</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By liuyuantao</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">扫描二维码,关注我们!了解更多全栈技能!<br/><img style="width:100px;height:100px;" src="/img/qrcode_for_gh_da91cebd00cc_258.jpg" ></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>